package com.yyx.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyx.server.mapper.MailLogMapper;
import com.yyx.server.pojo.Employee;
import com.yyx.server.pojo.MailConstants;
import com.yyx.server.pojo.MailLog;
import com.yyx.server.pojo.Notice;
import com.yyx.server.service.ElasticsearchService;
import com.yyx.server.service.EmployeeService;
import com.yyx.server.service.NoticeService;
import com.yyx.server.vo.MailVo;
import com.yyx.server.vo.NoticeVo;
import com.yyx.server.vo.ResultVo;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YongXin
 * @since 2021-10-02
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private ElasticsearchService elasticsearchService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;

    @ApiOperation("获取前四通知")
    @GetMapping("/newNotice")
    public NoticeVo getAll(){
        //新闻通告
        QueryWrapper<Notice> wrapper1 = new QueryWrapper<Notice>().eq("style", "新闻").orderByDesc("time").last("limit 4");
        List<Notice> list1 = noticeService.list(wrapper1);
        //通知通告
        QueryWrapper<Notice> wrapper2 = new QueryWrapper<Notice>().eq("style", "通知").orderByDesc("time").last("limit 4");
        List<Notice> list2 = noticeService.list(wrapper2);
        //人事通告
        QueryWrapper<Notice> wrapper3 = new QueryWrapper<Notice>().eq("style", "人事").orderByDesc("time").last("limit 4");
        List<Notice> list3 = noticeService.list(wrapper3);
        //制度通告
        QueryWrapper<Notice> wrapper4 = new QueryWrapper<Notice>().eq("style", "制度").orderByDesc("time").last("limit 4");
        List<Notice> list4 = noticeService.list(wrapper4);
        return new NoticeVo(list1,list2,list3,list4);
    }

    @ApiOperation("发布通告")
    @PutMapping("/addNotice")
    public ResultVo addNotice(@RequestBody Notice notice){
        notice.setTime(LocalDateTime.now());
        boolean b = noticeService.save(notice);
        if (b) {
            elasticsearchService.updEs();
            return ResultVo.success("发布成功！");
        }
        return ResultVo.error("发布失败！");
    }
    @ApiOperation("发送邮件")
    @PutMapping("/sendMail")
    public ResultVo sendMail(@RequestBody MailVo mailVo){
        String toMailEmpId = mailVo.getToMailEmp().getWorkId();
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("work_id",toMailEmpId);
        Employee employee = employeeService.getOne(wrapper);
        if (employee == null){
            return ResultVo.error("员工不存在！");
        }else if ("".equals(employee.getEmail())){
            return ResultVo.error("该员工未录入邮箱！");
        }
        String msgId = UUID.randomUUID().toString();
        MailLog mailLog = new MailLog();
        mailLog.setMsgId(msgId);
        mailLog.setEId(employee.getId());
        mailLog.setStatus(0);
        mailLog.setRouteKey(MailConstants.ROUTING_KEY);
        mailLog.setExchange(MailConstants.EXCHANGE);
        mailLog.setCount(0);
        //重试时间为当前时间加上消息超时时间
        mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
        mailLog.setCreateTime(LocalDateTime.now());
        mailLog.setUpdateTime(LocalDateTime.now());
        mailLogMapper.insert(mailLog);
        //发送消息
        MailVo gz = new MailVo(mailVo.getMailContent(),employee.getEmail(), employee,"GZ");
        rabbitTemplate.convertAndSend(MailConstants.EXCHANGE,MailConstants.ROUTING_KEY,gz,new CorrelationData(msgId));
        return ResultVo.success("发布成功！");
    }

    @ApiOperation("内容关键字搜索历史公告")
    @GetMapping("/search/{keyword}")
    public List<Notice> search(@PathVariable String keyword){
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //前置标签
        highlightBuilder.preTags("<span style='color: red;'>");
        //后置标签
        highlightBuilder.postTags("</span>");
        //高亮内容
        highlightBuilder.field("content");
        NativeSearchQuery nativeSearchQuery = nativeSearchQueryBuilder
                .withQuery(QueryBuilders.matchPhraseQuery("content", keyword))
                .withHighlightBuilder(highlightBuilder)
                .build();
        SearchHits<Notice> search = elasticsearchRestTemplate.search(nativeSearchQuery, Notice.class);
        ArrayList<Notice> list = new ArrayList<>();
        for (SearchHit<Notice> hit : search.getSearchHits()) {
            Notice notice = hit.getContent();
            notice.setContent(hit.getHighlightField("content").get(0));
            list.add(notice);
        }
        return list;
    }

}

